<template>
  <view
    v-if="isOpen"
    style="position: absolute; left: 0; top: 0; width: 750rpx"
    :style="{ height: `${maskHeight}px` }"
  >
    <!-- mask 区域 -->
    <view
      style="
        z-index: 65536;
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background-color: #333333c0;
      "
    ></view>
    <!-- body 区域 -->
    <view
      class="body"
      style="z-index: 65537; position: absolute; left: 0; width: 100%"
      :style="{
        transition: hasTransition ? 'all 300ms' : undefined,
        top: `${bodyTop}px`,
      }"
      @transitionend="transitionend"
    >
      <slot name="default"></slot>
    </view>
  </view>
</template>

<script>
import TopInfo from "@/utils/top-info";
import ElementInfo from "@/utils/element-info";
export default {
  name: "my-pop",
  props: {
    /**
     * 是否显示，外部通过控制 v-model 就可以显示和隐藏了
     * @type {boolean}
     */
    value: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      /**
       * 辅助打开判断
       */
      isOpen: false,
      /**
       * 遮罩层高度
       */
      maskHeight: TopInfo.getScreenHeight(),
      /**
       * body 的 top 值
       */
      bodyTop: TopInfo.getScreenHeight(),
      /**
       * 是否应用过渡效果
       */
      hasTransition: false,
    };
  },
  methods: {
    async hide() {
      this.hasTransition = true;
      // 设置 body 的 top 值为屏幕高度
      this.bodyTop = TopInfo.getScreenHeight();
    },
    // 缩回过渡完毕
    transitionend() {
      if (this.bodyTop === TopInfo.getScreenHeight()) {
        this.isOpen = false;
        this.$emit("input", false);
      }
    },
  },
  watch: {
    value(newValue, oldValue) {
      console.log("监控到 value 变化");
      if (!oldValue && newValue) {
        this.isOpen = true;
      }
      if (newValue) {
        this.hasTransition = false;
        // 设置 body 的 top 值为屏幕高度
        this.bodyTop = TopInfo.getScreenHeight();
        console.log("屏幕高度为", TopInfo.getScreenHeight());
        this.$nextTick(async () => {
          this.hasTransition = true;
          // 设置 body 的 top 值为 (屏幕高度 - 元素高度)
          this.bodyTop =
            TopInfo.getScreenHeight() -
            (await ElementInfo.getElementInfo(this, ".body")).height;
          console.log("最终停止的高度为", this.bodyTop);
        });
      } else {
        this.hide();
      }
    },
  },
};
</script>
